package com.itheima.controller;

import com.itheima.flag.Flag;
import com.itheima.pojo.Dept;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/depts")
public class DeptController {
    @Autowired
    private DeptService deptService;

    @GetMapping
    public Result selectDepts() {
        List<Dept> list = deptService.selectDepts();
        return Result.success(list);
    }

    /*获取请求中的参数的方式
        简单参数值得是直接通过?拼接写在后面的参数
        方式一: 使用HttpServletRequest request获取String id = request.getParameter("id");
        因操作繁琐,代码量很多,易出错等问题不推荐
        方式二 同个RequestParam注解 ,RequestParam有一个属性 required默认的是true必须传参
        如果不想传参, 可以将required的属性改为false
        方式三：如果请求参数名与形参变量名相同直接定义方法形参即可接收。，（省略RequestParam)
     */
//    @DeleteMapping("/depts")
//    public Result deleteById(HttpServletRequest request){
//        String id = request.getParameter("id");
//        Integer deleteId = Integer.valueOf("id");
//        System.out.println("删除的id是"+deleteId+"的部门");
//        return Result.success();
//    }
//    @DeleteMapping("/depts")
//    public Result deleteById(@RequestParam(value = "id", required = false) Integer id) {
//        System.out.println("删除的id是" + id + "的部门");
//        return Result.success();
    //}

    @DeleteMapping
    @Flag
    public Result deleteById(@RequestParam("id")  Integer id) {
        System.out.println("删除的id是" + id + "的部门");
        deptService.deleteById(id);
        return Result.success();
    }

    @PostMapping
    public Result insertDept(@RequestBody Dept dept) {
        System.out.println("新增部门 = " + dept);
        deptService.insertById(dept);
        return Result.success();
    }
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
       Dept dept = deptService.getById(id);
       return Result.success(dept);
    }
    @PutMapping
    public Result updateDept(@RequestBody Dept dept) {
        deptService.updateDept(dept);
        return Result.success();
    }

    //默认bean的作用域为   :singLeton(单例)
    public DeptController(){
        System.out.println("DeptController constructor -----------------");
    }
}
